package com.yxw.live_vod_backend_boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yxw.live_vod_backend_boot.dto.ReviewExamineDTO;
import com.yxw.live_vod_backend_boot.dto.ShopReviewDTO;
import com.yxw.live_vod_backend_boot.dto.ShopReviewQueryDTO;
import com.yxw.live_vod_backend_boot.entity.YxProductCategoryEntity;
import com.yxw.live_vod_backend_boot.entity.YxShopReviewEntity;
import com.yxw.live_vod_backend_boot.mapper.ProductCategoryMapper;
import com.yxw.live_vod_backend_boot.mapper.ShopReviewMapper;
import com.yxw.live_vod_backend_boot.service.ShopReviewService;
import com.yxw.live_vod_backend_boot.util.HuaWeiObsUtil;
import com.yxw.live_vod_backend_boot.util.PageUtils;
import com.yxw.live_vod_backend_boot.util.UserUtil;
import com.yxw.live_vod_backend_boot.vo.ShopReviewVO;
import com.yxw.live_vod_facade.dto.ShopAddDTO;
import com.yxw.live_vod_facade.dto.ShopExtendAddDTO;
import com.yxw.live_vod_facade.feign.FileFeignClient;
import com.yxw.live_vod_facade.feign.ShopFeignClient;
import com.yxw.live_vod_facade.feign.UserFeignClient;
import com.yxw.live_vod_facade.vo.ShopVO;
import com.yxw.live_vod_facade.vo.UserInfoVo;
import com.yxw.live_vod_facade.vo.YxFileVo;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.ErrorCodeEnum;
import com.yxw.yxnet_cd_center.common.enums.FileClassifyEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺审核管理Service业务层处理
 *
 * @author xiexuxin
 * @date 2023-11-28
 */
@Slf4j
@Service
public class ShopReviewServiceImpl extends ServiceImpl<ShopReviewMapper, YxShopReviewEntity> implements ShopReviewService {

    @Autowired
    private ShopReviewMapper shopReviewMapper;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private ShopFeignClient shopFeignClient;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Autowired
    private HuaWeiObsUtil huaWeiObsUtil;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductCategoryMapper categoryMapper;

    /**
     * 添加店铺审核
     *
     * @param addDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopReviewVO addShopReview(MultipartFile corporateCardFront, MultipartFile corporateCardReverse, MultipartFile corporateCardHand, MultipartFile shopAvatar, MultipartFile businessLicense, ShopReviewDTO addDTO) {
        LambdaQueryWrapper<YxShopReviewEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true, YxShopReviewEntity::getShopName, addDTO.getShopName());
        Integer count = shopReviewMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BaseException("店铺名称【" + addDTO.getShopName() + "】已存在，请修改名称");
        }
        BaseResult userInfo = userFeignClient.getUserInfo(addDTO.getUserId());
        ObjectMapper objectMapper = new ObjectMapper();
        UserInfoVo userInfoVo = objectMapper.convertValue(userInfo.getData(), UserInfoVo.class);
        YxShopReviewEntity shopReview = new YxShopReviewEntity();
        BeanUtils.copyProperties(addDTO, shopReview);
        shopReview.setUserId(userInfoVo.getUserId());
        shopReview.setUserName(userInfoVo.getUserName());
        shopReview.setUserPhone(userInfoVo.getPhone());
        shopReview.setCreateTime(new Date());
        int rows = shopReviewMapper.insert(shopReview);
        if (rows != 1) {
            throw new BaseException("添加店铺审核失败, 服务器忙, 请稍后重试!");
        }
        Long shopReviewId = shopReview.getShopReviewId();
        // 批量上传文件
        List<YxFileVo> fileInfos = batchUploadFiles(new MultipartFile[]{corporateCardFront, corporateCardReverse, corporateCardHand, shopAvatar, businessLicense}, shopReviewId);
        for (int i = 0; i < fileInfos.size(); i++) {
            YxFileVo fileInfo = fileInfos.get(i);
            if (fileInfo == null) {
                continue;
            }
            if (fileInfo.getFileUrl() != null && fileInfo.getObjectKey() != null) {
                switch (i) {
                    case 0:
                        shopReview.setCorporateCardFront(fileInfo.getFileUrl());
                        shopReview.setCorporateCardFrontKey(fileInfo.getObjectKey());
                        break;
                    case 1:
                        shopReview.setCorporateCardReverse(fileInfo.getFileUrl());
                        shopReview.setCorporateCardReverseKey(fileInfo.getObjectKey());
                        break;
                    case 2:
                        shopReview.setCorporateCardHand(fileInfo.getFileUrl());
                        shopReview.setCorporateCardHandKey(fileInfo.getObjectKey());
                        break;
                    case 3:
                        shopReview.setShopAvatar(fileInfo.getFileUrl());
                        shopReview.setShopAvatarKey(fileInfo.getObjectKey());
                        break;
                    case 4:
                        shopReview.setBusinessLicense(fileInfo.getFileUrl());
                        shopReview.setBusinessLicenseKey(fileInfo.getObjectKey());
                        break;
                    default:
                        break;
                }
            }
        }
        rows = shopReviewMapper.updateById(shopReview);
        if (rows != 1) {
            throw new BaseException("更新店铺审核失败，请稍后重试");
        }
        // 新增店铺信息
        ShopAddDTO shopAddDTO = new ShopAddDTO();
        shopAddDTO.setShopId(String.valueOf(shopReview.getShopId()));
        shopAddDTO.setShopName(shopReview.getShopName());
        shopAddDTO.setMerchantId(String.valueOf(shopReview.getMerchantId()));
        shopAddDTO.setMerchantName(shopReview.getMerchantName());
        shopAddDTO.setShopAvatar(shopReview.getShopAvatar());
        shopAddDTO.setUserId(shopReview.getUserId());
        shopAddDTO.setUserName(shopReview.getUserName());
        shopAddDTO.setPhone(shopReview.getUserPhone());
        shopAddDTO.setStatus(CommonConstant.ZERO);
        shopAddDTO.setAddress(addDTO.getShopAddress());
        ShopVO shopVO = addShop(shopAddDTO);
        shopReview.setShopId(shopVO.getLiveShopId());
        baseMapper.updateById(shopReview);
        ShopReviewVO vo = new ShopReviewVO();
        BeanUtils.copyProperties(shopReview, vo);
        return vo;
    }

    private List<YxFileVo> batchUploadFiles(MultipartFile[] files, Long shopId) {
        // 使用 Stream 过滤掉数组中的 null 值
        List<MultipartFile> validFiles = Arrays.stream(files)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        BaseResult<List<YxFileVo>> listBaseResult = null;
        try {
            listBaseResult = fileFeignClient.uploadFile(validFiles.toArray(new MultipartFile[0]), shopId, FileClassifyEnum.IMAGES_FILE.getCode(),"");
        } catch (Exception e) {
            throw new BaseException("文件上传失败，请稍后重试");
        }
        if (Integer.parseInt(listBaseResult.getResultCode()) != HttpStatus.SC_OK) {
            throw new BaseException("文件上传失败，请稍后重试");
        }
        List<YxFileVo> result = new ArrayList<>();
        int validFileIndex = 0;
        for (int i = 0; i < files.length; i++) {
            if (files[i] == null) {
                // 将 null 值添加到结果列表中
                result.add(null);
            } else {
                // 将非空值添加到结果列表中
                result.add(listBaseResult.getData().get(validFileIndex));
                validFileIndex++;
            }
        }
        return result;
    }

    /**
     * 更新店铺审核数据详情
     * @param shopReviewId
     * @param updateDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShopReview(MultipartFile corporateCardFront, MultipartFile corporateCardReverse, MultipartFile corporateCardHand, MultipartFile shopAvatar, MultipartFile businessLicense, Long shopReviewId, ShopReviewDTO updateDTO) {
        YxShopReviewEntity shopReview = shopReviewMapper.selectById(shopReviewId);
        if (null == shopReview){
            throw new BaseException("修改店铺审核信息失败, 尝试修改的店铺审核数据不存在!");
        }
        if (shopReview.getExamineStatus() != 0){
            throw new BaseException("修改店铺审核信息失败,当前店铺审核已完成,不能修改!");
        }
        LambdaQueryWrapper<YxShopReviewEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true, YxShopReviewEntity::getShopName, updateDTO.getShopName());
        Integer count = shopReviewMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BaseException("店铺名称【" + updateDTO.getShopName() + "】已存在，请修改名称");
        }
        BeanUtils.copyProperties(updateDTO, shopReview);
        shopReview.setUpdateTime(new Date());
        // 删除旧文件
        if (shopReview.getCorporateCardFrontKey() != null && corporateCardFront != null) {
            huaWeiObsUtil.deleteFile(shopReview.getCorporateCardFrontKey());
        }
        if (shopReview.getCorporateCardReverseKey() != null && corporateCardReverse != null) {
            huaWeiObsUtil.deleteFile(shopReview.getCorporateCardReverseKey());
        }
        if (shopReview.getCorporateCardHandKey() != null && corporateCardHand != null) {
            huaWeiObsUtil.deleteFile(shopReview.getCorporateCardHandKey());
        }
        if (shopReview.getShopAvatarKey() != null && shopAvatar != null) {
            huaWeiObsUtil.deleteFile(shopReview.getShopAvatarKey());
        }
        if (shopReview.getBusinessLicenseKey() != null && businessLicense != null) {
            huaWeiObsUtil.deleteFile(shopReview.getBusinessLicenseKey());
        }
        // 批量上传文件
        List<YxFileVo> fileInfos = batchUploadFiles(new MultipartFile[]{corporateCardFront, corporateCardReverse, corporateCardHand, shopAvatar, businessLicense}, shopReviewId);
        for (int i = 0; i < fileInfos.size(); i++) {
            YxFileVo fileInfo = fileInfos.get(i);
            if (fileInfo == null) {
                continue;
            }
            if (fileInfo.getFileUrl() != null && fileInfo.getObjectKey() != null) {
                switch (i) {
                    case 0:
                        shopReview.setCorporateCardFront(fileInfo.getFileUrl());
                        shopReview.setCorporateCardFrontKey(fileInfo.getObjectKey());
                        break;
                    case 1:
                        shopReview.setCorporateCardReverse(fileInfo.getFileUrl());
                        shopReview.setCorporateCardReverseKey(fileInfo.getObjectKey());
                        break;
                    case 2:
                        shopReview.setCorporateCardHand(fileInfo.getFileUrl());
                        shopReview.setCorporateCardHandKey(fileInfo.getObjectKey());
                        break;
                    case 3:
                        shopReview.setShopAvatar(fileInfo.getFileUrl());
                        shopReview.setShopAvatarKey(fileInfo.getObjectKey());
                        break;
                    case 4:
                        shopReview.setBusinessLicense(fileInfo.getFileUrl());
                        shopReview.setBusinessLicenseKey(fileInfo.getObjectKey());
                        break;
                    default:
                        break;
                }
            }
        }
        int rows = shopReviewMapper.updateById(shopReview);
        if (rows != 1) {
            throw new BaseException("修改店铺审核数据失败，服务器忙，请稍后再试！");
        }
    }

    /**
     * 根据id查询店铺审核数据详情
     * @param shopReviewId
     * @return
     */
    @Override
    public ShopReviewVO getShopReviewById(Long shopReviewId) {
        YxShopReviewEntity shopReview = shopReviewMapper.selectById(shopReviewId);
        ShopReviewVO shopReviewVO = new ShopReviewVO();
        BeanUtils.copyProperties(shopReview , shopReviewVO);
        return shopReviewVO;
    }

    /**
     * 根据店铺id查询店铺审核数据详情
     * @param shopId
     * @return
     */
    @Override
    public ShopReviewVO getShopReviewByShopId(Long shopId) {
        LambdaQueryWrapper<YxShopReviewEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true, YxShopReviewEntity::getShopId, shopId);
        YxShopReviewEntity yxShopReviewEntity = baseMapper.selectOne(queryWrapper);
        ShopReviewVO shopReviewVO = new ShopReviewVO();
        BeanUtils.copyProperties(yxShopReviewEntity , shopReviewVO);
        return shopReviewVO;
    }

    /**
     * 获取店铺审核数据列表
     * @param queryDTO
     * @return
     */
    @Override
    public PageVO<ShopReviewVO> getShopReviewList(ShopReviewQueryDTO queryDTO) {
        Page<ShopReviewVO> page = new Page<>(queryDTO.getCurrPage(),queryDTO.getPageSize());
        List<ShopReviewVO> list = shopReviewMapper.getShopReviewList(page,queryDTO);
        return PageUtils.get(page, list);
    }

    /**
     * 店铺具体审核
     * @param examineDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult isShopReview(ReviewExamineDTO examineDTO) {
        BaseResult baseResult = new BaseResult();
        if (null == examineDTO.getExamineStatus()){
            throw new BaseException("请给出审核意见!");
        }
        if (2 == examineDTO.getExamineStatus()) {
            String examineDescribe = examineDTO.getExamineDescribe();
            if (examineDescribe == null || examineDescribe.isEmpty()) {
                throw new BaseException("审核拒绝,请给出具体的审核意见!");
            }
        }
        YxShopReviewEntity shopReview = shopReviewMapper.selectById(examineDTO.getShopReviewId());
        if(shopReview == null){
            throw new BaseException("审核失败,当前审核数据不存在!");
        }
        YxProductCategoryEntity category = categoryMapper.selectById(shopReview.getCategoryId());
        if (category == null){
            throw new BaseException("审核失败,商品类目不存在!");
        }
        try {
//            NoticeTypeEnum type=null;
            // 审核通过
            if (1 == examineDTO.getExamineStatus()) {
                shopReview.setExamineStatus(1);
                shopReview.setExamineDescribe(examineDTO.getExamineDescribe());
                shopReview.setExamineTime(new Date());
//                shopReview.setExamineUserId(userUtil.getLoginUserVo().getUserId());
//                shopReview.setExamineUserName(userUtil.getLoginUserVo().getUserName());
                shopReviewMapper.updateById(shopReview);
                ShopExtendAddDTO extendAddDTO = new ShopExtendAddDTO();
                extendAddDTO.setShopId(String.valueOf(shopReview.getShopId()));
                extendAddDTO.setShopName(shopReview.getShopName());
                extendAddDTO.setCategoryId(String.valueOf(category.getCategoryId()));
                extendAddDTO.setCategoryName(category.getCategoryName());
                extendAddDTO.setCorporateCardFront(shopReview.getCorporateCardFront());
                extendAddDTO.setCorporateCardReverse(shopReview.getCorporateCardReverse());
                extendAddDTO.setCorporateCardHand(shopReview.getCorporateCardHand());
                extendAddDTO.setBusinessLicense(shopReview.getBusinessLicense());
                addShopExtend(extendAddDTO);
                updateShopStatus(shopReview.getShopId(), CommonConstant.ONE);
//                type = NoticeTypeEnum.HOME_PAGE_UPDATE_PASS;
            }else {
                // 审核拒绝
                if(StringUtils.isBlank(examineDTO.getExamineDescribe())){
                    throw new BaseException("审核拒绝时,拒绝原因必填");
                }
                shopReview.setExamineStatus(2);
                shopReview.setExamineDescribe(examineDTO.getExamineDescribe());
                shopReview.setExamineTime(new Date());
//                shopReview.setExamineUserId(userUtil.getLoginUserVo().getUserId());
//                shopReview.setExamineUserName(userUtil.getLoginUserVo().getUserName());
                shopReviewMapper.updateById(shopReview);
                updateShopStatus(shopReview.getShopId(), CommonConstant.TWO);
//                type = NoticeTypeEnum.HOME_PAGE_UPDATE_REFSE;
            }
//            try {
//                发送审核系统消息
//
//            } catch (Exception e) {
//                log.error("审核消息发送失败：==================================================>" + e.getMessage());
//            }
            baseResult = BaseResult.doSuccess(null, "审核成功");
        }catch (Exception e) {
            log.error("审核异常信息==================================================>" + e.getMessage());
            baseResult = BaseResult.failed(ErrorCodeEnum.UNKNOWN_ERROR, "审核异常信息:" + e.getMessage());
        }
        return baseResult;
    }

    @Override
    public ShopVO addShop(ShopAddDTO addDTO) {
        BaseResult<ShopVO> shopVOBaseResult = shopFeignClient.addShop(addDTO);
        return shopVOBaseResult.getData();
    }

    @Override
    public void addShopExtend(ShopExtendAddDTO addDTO) {
        shopFeignClient.addShopExtend(addDTO);
    }

    @Override
    public void updateShopStatus(Long shopId, Integer status) {
        shopFeignClient.updateShopStatus(shopId, status);
    }

}
